import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const MessageSchema = new mongoose.Schema({
    sender: Object,
    senderId: String,
    receiver: Object,
    receiverId: String,
    msg: String,
    createTime: Number
});

MessageSchema.methods.saveMessage = function (message, cb) {
    message.createTime = moment().unix();
    this.model('message').insertMany([message], cb);
};

MessageSchema.methods.getMessages = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const messageModel = this.model('message');
    messageModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        messageModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, messages) => cb(err, messages, count, hasMore));
    });
};

MessageSchema.methods.getAllMessages = function (query, cb) {
    // this.model('message').find(query, { name: 1, _id: 0 }, cb);
    this.model('message').find(query, cb);
};

MessageSchema.methods.getMessage = function (query, cb) {
    this.model('message').findOne(query, cb);
};

MessageSchema.methods.updateMessage = function (message, cb) {
    const _id = message._id;
    delete message._id;
    this.model('message').findOneAndUpdate({ _id }, { $set: message }, cb);
};

MessageSchema.methods.removeMessages = function (messageIds, cb) {
    this.model('message').remove({ _id: { $in: messageIds } }, cb);
};

export default db.model('message', MessageSchema);